import AVFoundation

class iKunSound {
    
    private static var player: AVPlayer?
    private static var names: [String] = ["ngm", "j", "n", "t", "m"]
    private static var isPlaying = false  // Track the playing state
    
    static func playIKun(index: Int = 0) {
        var index_ = index
        if (index_ < 0 || index_ > 4) {
            index_ = 0
        }

        if let filePath = Bundle.main.path(forResource: "\(names[index_])", ofType: "mp3") {
            let fileURL = URL(fileURLWithPath: filePath)
            playMP3(fileURL: fileURL)
            
            while (isPlaying) {
                Thread.sleep(forTimeInterval: TimeInterval(0.02))
            }
        }
    }

    private static func playMP3(fileURL: URL) {
        isPlaying = true
        
        // Create AVPlayer with the file URL
        player = AVPlayer(url: fileURL)
        
        // Register for the notification when the audio finishes
        NotificationCenter.default.addObserver(self, selector: #selector(audioDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
        
        // Start playing the audio
        player?.play()
    }

    // Selector to call when the audio finishes playing
    @objc private static func audioDidFinishPlaying(notification: Notification) {
        // After audio finishes, we mark it as not playing
        isPlaying = false
        
        // Remove the observer to prevent memory leaks
        NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
    }
}
